import axios from "axios";
import NproGress from "nprogress";
import { ElMessage } from "element-plus";
import "nprogress/nprogress.css";

// 开发环境        http://127.0.0.1:7001
// 测试环境        http://127.0.0.1:8001
// 预生产环境      http://pre-production:7001
// 生产环境        http://production:7001

// 50%  1

// npm run dev    development
// npm run build  production

// 白名单
const whiteList = ['/api/getCarTypeList', '/api/getVehicleList', '/api/getCarList']

// 请求拦截
axios.interceptors.request.use((config) => {
  // 开启进度条
  NproGress.start();
  // 添加token信息
  config.headers.Authorization = sessionStorage.getItem("token")?sessionStorage.getItem("token"):''
  return config;
});


// 响应拦截
axios.interceptors.response.use((data) => {
  // 只有状态码为200才会走进该函数
  // 关闭进度条
  NproGress.done();
  // 消息提示
  if (data.data.code === 0) {
    ElMessage({
      message: data.data.msg,
      type: "warning",
    });
  } else if (data.data.code === 1) {
    // data.config.url
    const flag = whiteList.includes(data.config.url)
    if (!flag) {
      ElMessage({
        message: data.data.msg,
        type: "success",
      });
    }
  }
  return data;
}, (error) => {
  // 200以外的状态码
  switch(error.response.status) {
    case 500:
      ElMessage({
        message: '服务器内部错误',
        type: "error",
      });
    break;
    case 404:
      ElMessage({
        message: '地址或请求方式不正确',
        type: "error",
      });
    break;
  }
});

export default axios;
